//
//  AppDelegate.m
//  UADE-Mobile
//
//  Created by Marcos Damian Pianelli on 9/13/11.
//  Copyright (c) 2011 DG. All rights reserved.
//

#import "AppDelegate.h"
#import "StyleSheet.h"
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "CourseDetailViewController.h"
#import "DownloadViewController.h"
#import "DownloadDetailViewController.h"
#import "NewsViewController.h"
#import "GroupsViewController.h"
#import "MessagesViewController.h"
#import "NotificationsViewController.h"
#import "NotificationsHelper.h"
#import "MBProgressHUD.h"
#import "HomeViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize homeViewController;

NSDictionary* notif = nil;
MBProgressHUD * progressHUD; 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    homeViewController = nil;
    TTNavigator* navigator = [TTNavigator navigator];
    navigator.supportsShakeToReload = YES;
    navigator.persistenceMode = TTNavigatorPersistenceModeNone;
    navigator.window = self.window;
    
    [TTStyleSheet setGlobalStyleSheet:[[StyleSheet alloc] init]];
    
    
    TTURLMap* map = navigator.URLMap;
    [map from:@"*" toViewController:[TTWebController class]];
    [map from:@"tt://nib/(loadFromNib:)" toSharedViewController:self];
    [map from:@"tt://nib/(loadFromNib:)/(withClass:)" toSharedViewController:self];
    [map from:@"tt://viewController/(loadFromVC:)" toSharedViewController:self];
    [map from:@"tt://modal/(loadFromNib:)" toModalViewController:self];
    
    [map from:@"tt://home" toViewController:[HomeViewController class]];
    [map from:@"tt://detail" toViewController:[CourseDetailViewController class]];
    [map from:@"tt://download/(initWithID:)" toViewController:[DownloadViewController class]];
    [map from:@"tt://download" toViewController:[DownloadViewController class]];
    [map from:@"tt://news/(initWithID:)" toViewController:[NewsViewController class]];
    [map from:@"tt://foro/(initWithID:)" toViewController:[GroupsViewController class]];
    [map from:@"tt://messages/(initWithGroupID:)" toViewController:[MessagesViewController class]];
    [map from:@"tt://downloadDetail" toViewController:[DownloadDetailViewController class]];
    [map from:@"tt://notifications" toSharedViewController:[NotificationsViewController class]];
        
    NSDictionary* notification;
    
    if (launchOptions != nil)
    {
        NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        notification = dictionary;
        if (dictionary != nil)
        {
            NSLog(@"Launched from push notification: %@", dictionary);
        }
    }    
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    BOOL ackNotSent = [prefs boolForKey:@"ackNotSent"];
    if (ackNotSent){
        
        NotificationsHelper* helper = [[NotificationsHelper alloc ] init];
        [helper sendAck];
        ackNotSent = NO;
        [prefs setBool:ackNotSent forKey:@"ackNotSent"];
        [prefs synchronize];
    }

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
    
    NSString* noti = [[NSString alloc] initWithFormat:@"%@", @"{\"TipoNotificacion\":1,\"IdAula\":137490,\"IdGrupo\":0,\"IdArchivoString\":\"\",\"FechaHoraNotificacion\":\"\/Date(-62135586000000-0300)\/\",\"Fecha\":\"\/Date(-1198908717056-0300)\/\",\"FechaEvento\":\"\/Date(-62135586000000-0300)\/\",\"Cantidad\":0}"];

    NSLog(@"notif: %@", noti);
    NSUserDefaults *prefsss = [NSUserDefaults standardUserDefaults];
    NSMutableArray* notificationss = (NSMutableArray*)[prefsss objectForKey:@"notifications"];
    NSMutableArray* notifications = [notificationss mutableCopy];
    if (notifications == nil){
        notifications = [[NSMutableArray alloc]init];
    }
    
    [notifications addObject:[noti JSONValue]];
    [prefsss setObject:[notifications mutableCopy] forKey:@"notifications"];
    [prefsss synchronize];
    

/*    NotificationsHelper* helper = [[NotificationsHelper alloc] init];
    [helper didGetNotification:notif];
//*/
  //  notification = [noti JSONValue];
    
    TTURLAction *action = [[
                            [TTURLAction actionWithURLPath:@"tt://home"] 
                            applyQuery:[NSDictionary dictionaryWithObjectsAndKeys:
                                        notification, 
                                        @"notification", 
                                        nil]] 
                           applyAnimated:YES];
    [navigator openURLAction:action];

    
    /*if (![navigator restoreViewControllers]) {
    NSString* homeURL = [NSString stringWithFormat:@"tt://home/HomeViewController/%@", notification];
    [navigator openURLAction:[TTURLAction actionWithURLPath:homeURL]];
    /}*/
    
    return TRUE;
    
    
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    if (true){
        notif = userInfo;
        //NSLog(@"%@", userInfo);
        NSString *cancelTitle = @"Cerrar";
        NSString *showTitle = @"Ver";
        NSString *message = nil;
        id alert = [[userInfo valueForKey:@"aps"] valueForKey:@"alert"];
        if ([alert isKindOfClass:[NSString class]]) {
            message = alert;
        } else if ([alert isKindOfClass:[NSDictionary class]]) {
            message = NSLocalizedString([alert objectForKey:@"loc-key"], @"");
        }

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"WebCampus"
                                                            message:message 
                                                           delegate:self 
                                                  cancelButtonTitle:cancelTitle 
                                                  otherButtonTitles:showTitle, nil];
        [alertView show];
    }
    
}


// Delegation methods
- (void)application:(UIApplication *)app 

    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {

    NSString * token = [[[[devToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"Did register from remote Notification with token : %@", token);
    [self sendProviderDeviceToken:token]; // custom method
    
}

-(void)sendProviderDeviceToken:(NSString *)devToken{

    NSString * userHash = [[NSUserDefaults standardUserDefaults] objectForKey:@"hash"];

    [[NSUserDefaults standardUserDefaults] setObject:devToken forKey:@"token"];
    if (userHash == nil) {
        return;
    }
    
    //NSLog(@"token %@", devToken);
    NSString * urlStr = [NSString stringWithFormat:kPushSubscribe,userHash,devToken];
    //NSLog(@"url %@", urlStr);
    NSURLRequest * request =  [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    
    NSError* error = nil;
    NSURLResponse  *response = nil;
    
    NSData *result = [NSURLConnection sendSynchronousRequest:request
                                           returningResponse:&response
                                                       error:&error];
    
    NSString *resultado = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];

    
    if (error) {
        NSLog(@"error %@", error);
    }
    
    NSLog(@"Data: %@", resultado);
    
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error in registration. Error: %@", err); 
}

-(void)didLogin{
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"token"] != nil) {
        [self sendProviderDeviceToken:[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]];
    }
}

#pragma mark - Alert View Protocol 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
                [self performSelectorOnMainThread:@selector(initProgressHUD) withObject:nil waitUntilDone:YES];
        NSLog(@"Received notification: %@", notif);
        NotificationsHelper* helper = [[NotificationsHelper alloc] init];
        [helper performSelectorInBackground:@selector(notificationArrived:) withObject:notif];
    }    
}

-(void) hideProgressHUD{
    if (progressHUD != nil) {
        [progressHUD hide:TRUE];
        [progressHUD removeFromSuperview];
        progressHUD = nil;
    }
}

-(void) initProgressHUD{

    if (homeViewController != nil) {
        progressHUD = [[MBProgressHUD alloc] initWithView:[[[TTNavigator navigator] visibleViewController] view]];
        [[[[TTNavigator navigator] visibleViewController] view] addSubview:progressHUD];
        
        progressHUD.labelText = NSLocalizedString(@"Loading...", @"");
        [progressHUD show:true];
    }
}


///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Loads the given viewcontroller from the nib
 */
- (UIViewController*)loadFromNib:(NSString *)nibName withClass:className {
    UIViewController* newController = [[NSClassFromString(className) alloc]
                                       initWithNibName:nibName bundle:nil];
    
    return newController;
}


///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Loads the given viewcontroller from the the nib with the same name as the
 * class
 */
- (UIViewController*)loadFromNib:(NSString*)className {
    return [self loadFromNib:className withClass:className];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Loads the given viewcontroller by name
 */
- (UIViewController *)loadFromVC:(NSString *)className {
    UIViewController * newController = [[ NSClassFromString(className) alloc] init];
    
    return newController;
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)URL {
    [[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:URL.absoluteString]];
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    [[self homeViewController] performSelector:@selector(refresh)];

}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

@end
